package com.yanze.schoolinformation.viewModule;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yanze.schoolinformation.app.C;
import com.yanze.schoolinformation.model.bean.resp.RespHomeBanner;
import com.yanze.schoolinformation.model.http.DeforObserver;
import com.yanze.schoolinformation.model.http.cache.ACache;
import com.yanze.schoolinformation.model.http.reqo.DataReqo;
import com.yanze.schoolinformation.model.bean.NewsModule;
import com.yanze.schoolinformation.utils.TimeUtil;
import com.yanze.schoolinformation.view.home.HomeFragment;
import com.yanze.schoolinformation.viewModule.school_news.HomeNavigator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by MrZheng on 2018/3/16.
 */

public class HomeViewModule {
    private HomeFragment mFragment;
    private HomeNavigator mNavigator;
    private final ACache aCache;

    public HomeViewModule(HomeFragment fragment, HomeNavigator navigator) {
        this.mFragment = fragment;
        mNavigator = navigator;
        aCache = ACache.get(mFragment.getActivity());
    }

    //获取banner图
    public void getBanner() {
        String bannerjson = aCache.getAsString(C.key.Home_Banner);
        if (bannerjson != null) {
            RespHomeBanner entity = new Gson().fromJson(bannerjson, RespHomeBanner.class);
            mNavigator.getBannerSuccess(entity.getData());
            return;
        }
        DataReqo.getInstant().getHomeBanner(C.url.API_School)
                .subscribe(new DeforObserver<RespHomeBanner>() {
                    @Override
                    public void _onSubscribe(Disposable disposable) {
                        mFragment.addDisposable(disposable);
                    }

                    @Override
                    public void _onNext(RespHomeBanner entity) {
                        if (entity != null
                                && entity.getData() != null
                                && !entity.getData().isEmpty()) {
                            aCache.put(C.key.Home_Banner, new Gson().toJson(entity), (60 * 60 * 24));//一天
                            mNavigator.getBannerSuccess(entity.getData());
                        } else {
                            mNavigator.getBannerFaild();
                        }
                    }

                    @Override
                    public void _onError(String msg) {
                        mNavigator.getBannerFaild();
                    }
                });
    }

    //请求网络,解析网页
    public void getXuHaiData() {
        String newsjson = aCache.getAsString(C.key.Home_News);
        if (newsjson != null) {
            List<NewsModule> newsModules = new Gson().fromJson(newsjson, new TypeToken<List<NewsModule>>() {
            }.getType());
            mNavigator.getNewsSuccess(newsModules);
            return;
        }

        Observable.create(new ObservableOnSubscribe<List<NewsModule>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<NewsModule>> sub) throws Exception {
                List<NewsModule> temp = new ArrayList<>();
                NewsModule top = getXuHaiTop();
                temp.add(top);
                List<NewsModule> cont = getXuHaiContent();
                temp.addAll(cont);
                sub.onNext(temp);
                sub.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<NewsModule>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mFragment.addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull List<NewsModule> newsModules) {
                        mNavigator.showSuccessContint();
                        if (newsModules != null
                                && !newsModules.isEmpty()) {
                            String newsjson = new Gson().toJson(newsModules, new TypeToken<List<NewsModule>>() {
                            }.getType());
                            aCache.put(C.key.Home_News, newsjson, (60 * 60 * 24));
                            mNavigator.getNewsSuccess(newsModules);
                        } else {
                            mNavigator.getNewsFaild();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mNavigator.getNewsFaild();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    //获取徐海官网的顶部 1. 大图链接 2. 标语 3. 标语链接
    private NewsModule getXuHaiTop() throws IOException {
        Document document = Jsoup.connect(C.url.XuHaiUrl).timeout(5000).get();
        Element focus = document.getElementsByClass("wp-wrapper wp-focus").first();
        Element focus1 = focus.getElementsByClass("wp-inner").first();
        Element focus2 = focus1.getElementsByTag("div").first();
        Element focus3 = focus2.getElementsByTag("div").first();
        Element focus4 = focus3.getElementById("wp_news_w2");
        Element focus5 = focus4.getElementsByClass("focus").first();
        Element focusImg = focus5.getElementsByTag("img").first();
        String src = focusImg.attr("src");
        String a = focusImg.attr("data-focus-title");
        String str1 = a.split("href='")[1];
        String str2 = str1.split("' target='_blank'")[0];
        String str3 = a.split("title='")[1];
        String str4 = str3.split("'>")[0];
        NewsModule top = new NewsModule(str4, document.baseUri() + str2, document.baseUri() + src, NewsModule.IMAGE_ITEM);
        return top;
    }

    //获取徐海官网主题部分
    private List<NewsModule> getXuHaiContent() throws IOException {
        List<NewsModule> contNewsModule = new ArrayList<>();
        Document document = Jsoup.connect(C.url.xihaiUrl).get();
        Element fucous = document.getElementsByClass("wp-wrapper wp-container").first();
        Element fucous1 = fucous.getElementsByClass("wp-inner clearfix").first();
        Element fucous2 = fucous1.getElementsByClass("m-main clearfix").first();
        Element content = fucous2.getElementsByClass("content clearfix").first();

        Element left_cont = content.getElementsByClass("cbox-left").first();
        Element left_cont1 = left_cont.getElementsByTag("div").first();
        List<NewsModule> temp1 = getHeadOrBody(left_cont1);//通知公告
        Element right_cont = content.getElementsByClass("cbox-right").first();
        Element right_cont1 = right_cont.getElementsByTag("div").first();
        List<NewsModule> temp2 = getHeadOrBody(right_cont1);//徐海新闻

        //校园活动与学子之星模块
        Element school = fucous2.getElementsByClass("sidebar").first();
        Element school_cont = school.getElementsByTag("div").first();
        List<NewsModule> temp3 = getHeadOrBody(school_cont.getElementsByClass("wp-post post-31").first());
        List<NewsModule> temp4 = getHeadOrBody(school_cont.getElementsByClass("wp-post post-32").first());
        contNewsModule.addAll(temp1);//通知公告
        contNewsModule.addAll(temp2);//徐海新闻
        contNewsModule.addAll(temp3);//校园活动
        contNewsModule.addAll(temp4);//学子之星
        return contNewsModule;
    }

    //解析head与body模块
    private List<NewsModule> getHeadOrBody(Element content) {
        List<NewsModule> tempNews = new ArrayList<>();
        Element head = content.getElementsByClass("post-head").first();//head
        Element body = content.getElementsByClass("post-body").first();//body

        Element headbar = head.getElementsByClass("head-bar").first();
        String title = headbar.getElementsByTag("h3").text();
//        Log.e("log", title);
//        newsModule.setTitle(title);//标题

        Element title_more = headbar.getElementsByClass("post-more").first();
        Element title_more_a = title_more.getElementsByTag("a").first();
        String title_more_a_src = title_more_a.attr("href");
//        Log.e("log", head.baseUri() + title_more_a_src);
//        newsModule.setLink(head.baseUri() + title_more_a_src);
        tempNews.add(new NewsModule(title, title_more_a_src, "", NewsModule.TITLE_ITEM));//添加标题

        Element body1 = body.getElementsByTag("div").first();
        Element news_list = body1.getElementsByTag("ul").first();
        Elements news_lists = news_list.getElementsByTag("li");
        for (Element news : news_lists) {
            Element span1 = news.getElementsByClass("item-meta meta-title").first();
            Element news_a = span1.getElementsByTag("a").first();
            String news_a_title = news_a.attr("title");
//            Log.e("log", news_a_title);
            String news_a_hre = news_a.attr("href");
//            Log.e("log", body.baseUri() + news_a_hre);
            tempNews.add(new NewsModule(news_a_title, body.baseUri() + news_a_hre, "", NewsModule.NORMAL_ITEM));
        }
        return tempNews;
    }

    public void onDestory() {
        mNavigator = null;
        mFragment = null;
    }

    /**
     * 获取当天日期
     */
    public static ArrayList<String> getTodayTime() {
        String data = TimeUtil.getData();
        String[] split = data.split("-");
        String year = split[0];
        String month = split[1];
        String day = split[2];
        ArrayList<String> list = new ArrayList<>();
        list.add(year);
        list.add(month);
        list.add(day);
        return list;
    }
}
